package com.yfq.springframework.beans;

import java.lang.reflect.Constructor;

/**
 * @author 姚凤桥
 * @date 2022/11/14 21:09
 * @description
 */
public abstract class AbstractAutowiredCapableBeanFactory extends AbstractBeanFactory {
    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Constructor<?> constructorToUse = null;

        Constructor<?>[] constructors = beanDefinition.getBeanClass().getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            if (args != null && parameterTypes.length == args.length) {
                constructorToUse = constructor;
                break;
            }
        }

        Object bean = getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
        registerSingletonBean(beanName, bean);
        return bean;
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    /**
     * 通过配置来指定使用哪种实例化策略
     */
    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

}
